package com.jqb.dom;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.junit.Test;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

public class Sax {
	
	@Test
	public void testSax() throws Exception {
		saxXmlParse();
		saxParse();
	}

	public static void saxParse() throws ParserConfigurationException, SAXException, IOException {
		SAXParserFactory sax = SAXParserFactory.newInstance();
		SAXParser parser = sax.newSAXParser();
		parser.parse(new File("src/test/resources/users.xml"), new DefaultHandler(){
			@Override
			public void startDocument() throws SAXException {
				System.out.println("SAX starts parsing...");
			}
			@Override
			public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
				if("name".equals(qName)){
					System.out.print("name=");
				}
				if("id".equals(attributes.getLocalName(0))){
					System.out.println("id="+attributes.getValue(0));
				}
			}
			@Override
			public void characters(char[] ch, int start, int length)throws SAXException {
				System.out.println(new String(ch,start,length));
			}
		});
	}

	public static void saxXmlParse() throws ParserConfigurationException, SAXException, IOException, FileNotFoundException {
		SAXParserFactory sax = SAXParserFactory.newInstance();
		SAXParser parser = sax.newSAXParser();
		XMLReader xr = parser.getXMLReader();
		/*设置事件处理器*/
		xr.setContentHandler(new DefaultHandler(){
			@Override
			public void startDocument() throws SAXException {
				System.out.println("SAX starts parsing...");
			}
			@Override
			public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
				if("name".equals(qName)){
					System.out.print("name=");
				}
				if("id".equals(attributes.getLocalName(0))){
					System.out.println("id="+attributes.getValue(0));
				}
			}
			@Override
			public void characters(char[] ch, int start, int length) throws SAXException {
				System.out.println(new String(ch,start,length));
			}
		});
		/*解析*/
		xr.parse(new InputSource(new FileInputStream(new File("src/test/resources/users.xml"))));
	}
}
